from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.db import models
from django.utils.html import format_html
from django.shortcuts import redirect
from django.urls import reverse, path
from .models import UserProfile, ExpLog, Task, UserTask, Achievement, UserAchievement, Title, TemporaryPassword, FeatureSwitch

# 自定义用户资料内联编辑
class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = '用户资料'
    fields = ('bio', 'location', 'birth_date', 'avatar', 'level', 'exp', 'total_exp', 'title')
    readonly_fields = ('level', 'total_exp')

# 扩展用户管理
class UserAdmin(BaseUserAdmin):
    inlines = (UserProfileInline,)
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'date_joined', 'get_code_count', 'get_battle_count')
    list_filter = ('is_staff', 'is_superuser', 'is_active', 'date_joined')
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('-date_joined',)
    actions = ['reset_user_password']
    
    def get_code_count(self, obj):
        """获取用户代码数量"""
        return obj.codes.count()
    get_code_count.short_description = '代码数量'
    
    def get_battle_count(self, obj):
        """获取用户对战次数"""
        from battles.models import Battle
        return Battle.objects.filter(models.Q(player1=obj) | models.Q(player2=obj)).count()
    get_battle_count.short_description = '对战次数'
    
    def reset_user_password(self, request, queryset):
        """重置用户密码"""
        if queryset.count() != 1:
            self.message_user(request, "请选择一个用户进行密码重置", level='error')
            return
        
        user = queryset.first()
        return redirect(reverse('accounts:admin_reset_password', args=[user.id]))
    
    reset_user_password.short_description = "重置选中用户的密码"
    
    def get_urls(self):
        """覆盖默认的URL配置，重定向密码修改到我们的临时密码功能"""
        urls = super().get_urls()
        custom_urls = [
            path(
                '<id>/password/',
                self.admin_site.admin_view(self.user_change_password),
                name='auth_user_password_change',
            ),
        ]
        return custom_urls + urls
    
    def user_change_password(self, request, id, form_url=''):
        """重定向到我们的临时密码重置页面"""
        return redirect(reverse('accounts:admin_reset_password', args=[id]))

# 注册用户资料管理
@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'level', 'exp', 'total_exp', 'title', 'location', 'birth_date', 'get_avatar_preview')
    list_filter = ('level', 'location', 'title')
    search_fields = ('user__username', 'user__email', 'location', 'title')
    readonly_fields = ('get_avatar_preview', 'total_exp')
    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'bio', 'location', 'birth_date', 'avatar', 'get_avatar_preview')
        }),
        ('经验值系统', {
            'fields': ('level', 'exp', 'total_exp', 'title')
        }),
    )
    
    def get_avatar_preview(self, obj):
        """头像预览"""
        if obj.avatar:
            return f'<img src="{obj.avatar.url}" width="50" height="50" style="border-radius: 50%;"/>'
        return '无头像'
    get_avatar_preview.short_description = '头像预览'
    get_avatar_preview.allow_tags = True

# 重新注册User模型
admin.site.unregister(User)
admin.site.register(User, UserAdmin)


# 经验值日志管理
@admin.register(ExpLog)
class ExpLogAdmin(admin.ModelAdmin):
    list_display = ('user', 'amount', 'reason', 'level_before', 'level_after', 'created_at')
    list_filter = ('level_before', 'level_after', 'created_at')
    search_fields = ('user__username', 'reason')
    readonly_fields = ('user', 'amount', 'reason', 'level_before', 'level_after', 'created_at')
    ordering = ('-created_at',)
    
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False


@admin.register(FeatureSwitch)
class FeatureSwitchAdmin(admin.ModelAdmin):
    list_display = ('get_switch_display', 'is_enabled', 'updated_by', 'updated_at')
    list_filter = ('is_enabled', 'switch_key', 'updated_at')
    search_fields = ('switch_key', 'disabled_message')
    readonly_fields = ('updated_by', 'updated_at', 'created_at')
    ordering = ('switch_key',)
    
    fieldsets = (
        ('功能开关设置', {
            'fields': ('switch_key', 'is_enabled')
        }),
        ('提示信息', {
            'fields': ('disabled_message',),
            'description': '当功能关闭时显示给用户的提示信息'
        }),
        ('更新信息', {
            'fields': ('updated_by', 'updated_at', 'created_at'),
            'classes': ('collapse',)
        }),
    )
    
    def get_switch_display(self, obj):
        """显示开关名称"""
        return obj.get_switch_key_display()
    get_switch_display.short_description = '功能开关'
    
    def save_model(self, request, obj, form, change):
        """保存时记录更新者"""
        obj.updated_by = request.user
        super().save_model(request, obj, form, change)
    
    def get_urls(self):
        """添加自定义URL"""
        urls = super().get_urls()
        custom_urls = [
            path('feature-switches-manager/', 
                 self.admin_site.admin_view(self.feature_switches_manager_view),
                 name='feature_switches_manager'),
        ]
        return custom_urls + urls
    
    def feature_switches_manager_view(self, request):
        """功能开关管理视图"""
        from django.shortcuts import redirect
        return redirect('/accounts/admin/feature_switches/')
    
    def changelist_view(self, request, extra_context=None):
        """重写changelist视图，添加自定义管理按钮"""
        extra_context = extra_context or {}
        extra_context['feature_switches_manager_url'] = '/accounts/admin/feature_switches/'
        return super().changelist_view(request, extra_context=extra_context)


# 任务管理
@admin.register(Task)
class TaskAdmin(admin.ModelAdmin):
    list_display = ('title', 'task_type', 'target_count', 'exp_reward', 'is_active', 'created_at')
    list_filter = ('task_type', 'is_active', 'created_at')
    search_fields = ('title', 'description')
    ordering = ('-created_at',)
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description', 'task_type')
        }),
        ('任务设置', {
            'fields': ('target_count', 'exp_reward', 'is_active')
        }),
    )


# 用户任务管理
@admin.register(UserTask)
class UserTaskAdmin(admin.ModelAdmin):
    list_display = ('user', 'task', 'current_count', 'progress_percentage', 'status', 'started_at', 'completed_at')
    list_filter = ('status', 'task__task_type', 'started_at', 'completed_at')
    search_fields = ('user__username', 'task__title')
    readonly_fields = ('progress_percentage', 'started_at')
    ordering = ('-started_at',)
    
    def progress_percentage(self, obj):
        return f"{obj.progress_percentage:.1f}%"
    progress_percentage.short_description = '完成进度'


# 成就管理
@admin.register(Achievement)
class AchievementAdmin(admin.ModelAdmin):
    list_display = ('title', 'achievement_type', 'condition_key', 'condition_value', 'exp_reward', 'is_hidden', 'is_active')
    list_filter = ('achievement_type', 'is_hidden', 'is_active', 'created_at')
    search_fields = ('title', 'description', 'condition_key')
    ordering = ('-created_at',)
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description', 'achievement_type', 'icon')
        }),
        ('达成条件', {
            'fields': ('condition_key', 'condition_value')
        }),
        ('奖励设置', {
            'fields': ('exp_reward', 'is_hidden', 'is_active')
        }),
    )


# 用户成就管理
@admin.register(UserAchievement)
class UserAchievementAdmin(admin.ModelAdmin):
    list_display = ('user', 'achievement', 'achieved_at')
    list_filter = ('achievement__achievement_type', 'achieved_at')
    search_fields = ('user__username', 'achievement__title')
    readonly_fields = ('user', 'achievement', 'achieved_at')
    ordering = ('-achieved_at',)
    
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False


# 称号管理
@admin.register(Title)
class TitleAdmin(admin.ModelAdmin):
    list_display = ('name', 'condition_level', 'condition_achievement', 'get_color_preview', 'is_active')
    list_filter = ('condition_level', 'is_active', 'created_at')
    search_fields = ('name', 'description')
    ordering = ('condition_level', 'name')
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'color')
        }),
        ('获得条件', {
            'fields': ('condition_level', 'condition_achievement')
        }),
        ('设置', {
            'fields': ('is_active',)
        }),
    )
    
    def get_color_preview(self, obj):
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>',
            obj.color,
            obj.name
        )
    get_color_preview.short_description = '颜色预览'


# 临时密码管理
@admin.register(TemporaryPassword)
class TemporaryPasswordAdmin(admin.ModelAdmin):
    list_display = ('user', 'temp_password', 'created_by', 'created_at', 'expires_at', 'is_used')
    list_filter = ('is_used', 'created_at', 'expires_at')
    search_fields = ('user__username', 'created_by__username')
    readonly_fields = ('user', 'temp_password', 'created_by', 'created_at', 'expires_at', 'is_used')
    ordering = ('-created_at',)
    
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False
